package com.soilflow.web.controller.dahu.web;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.soilflow.common.constant.Constants;
import com.soilflow.common.constant.UserConstants;
import com.soilflow.common.core.domain.AjaxResult;
import com.soilflow.common.core.domain.entity.SysUser;
import com.soilflow.common.core.domain.model.LoginBody;
import com.soilflow.common.domain.ColorfulUser;
import com.soilflow.common.domain.DahuBusiness;
import com.soilflow.common.domain.dto.DahuBusinessDto;
import com.soilflow.common.utils.NoUtils;
import com.soilflow.common.utils.SecurityUtils;
import com.soilflow.common.utils.StringUtils;
import com.soilflow.framework.web.service.SysLoginService;
import com.soilflow.system.mapper.DahuBusinessMapper;
import com.soilflow.system.service.IDahuBusinessService;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Base64Utils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.AlgorithmParameterSpec;
import java.util.Map;
import java.util.Set;

import static com.soilflow.common.utils.SecurityUtils.getUsername;

@RestController
@RequestMapping("/reception/dahu")
public class DahuLoginController {
    @Autowired
    private SysLoginService loginService;
    @Autowired
    private IDahuBusinessService businessService;
    @Resource
    private DahuBusinessMapper businessMapper;
    /**
     * 登录
     */
    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginBody loginBody) {
        AjaxResult ajax = AjaxResult.success();
        String username = loginBody.getUsername()+"_dahu";
        System.out.println("loginBody.getUsername() = " + loginBody.getUsername());
        // 生成令牌
        String token = loginService.login(username, loginBody.getPassword(), loginBody.getCode(),
                loginBody.getUuid());
        ajax.put(Constants.TOKEN, token);
        System.out.println("token = " + token);
        return ajax;
    }
    /**
     * 注册
     */
    @PostMapping("/register")
    public AjaxResult login(@RequestBody DahuBusinessDto business) {
        System.out.println("user111"+business);
        if (UserConstants.NOT_UNIQUE.equals(businessService.checkUserNameUnique(business.getName())))
        {
            return AjaxResult.error("新增用户'" + business.getName() + "'失败，登录账号已存在");
        }
        else if (StringUtils.isNotEmpty(business.getPhone())
                && UserConstants.NOT_UNIQUE.equals(businessService.checkPhoneUnique(business)))
        {
            return AjaxResult.error("新增用户'" + business.getName() + "'失败，手机号码已存在");
        }
//        business.setCreateBy(getUsername());
        business.setPassword(SecurityUtils.encryptPassword(business.getPassword()));
        System.out.println("business = " + business);
        int b = businessMapper.addDahuBusiness(business);
        System.out.println("save = " + b);
        return AjaxResult.success();
    }

    @PostMapping("/openid/phone")
    public AjaxResult getOpenIDAndPhone(@RequestBody Map<String, Object> map) throws Exception {
        String appid = "wxf418b92aa77a62f4";
        String secret = "f2b96e7ba5b3918348623bbe1b034762";
        String openid = "";
        String sessionKey = "";
        String phone = "";
        String jscode = map.get("jscode").toString();
        String encrypt = map.get("encrypt").toString();
        String iv = map.get("iv").toString();
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appid +
                "&secret=" + secret + "&js_code=" + jscode + "&grant_type=authorization_code";
        String data = "";
        AjaxResult ajax = AjaxResult.success();
        try {
            data = httpGet(url);
            System.out.println("data = " + data);
            JSONObject jsonObject = JSON.parseObject(data);
            sessionKey = jsonObject.getString("session_key");
            openid=jsonObject.getString("openid");
            System.out.println("sessionKey = " + sessionKey);
            phone = getWxMiniPhone(sessionKey, iv, encrypt);
            if (phone != null && !phone.equals("")) {
                DahuBusiness user = businessService.getPhonenumber(phone);
                if(!ObjectUtils.isEmpty(user)){
                    ajax.put(Constants.TOKEN, loginService.loginByUserName(user.getName()+"_dahu"));
                    ajax.put("phone", phone);
                    ajax.put("userId", user.getId());
                    ajax.put("users",user);
                }else {
                    DahuBusiness business = new DahuBusiness();
                    business.setPhone(phone);
                    business.setOpenid(openid);
                    business.setName(phone);
                    boolean save = businessService.save(business);
                    if (save) {
                        return AjaxResult.success("新增成功");
                    }else {
                        return AjaxResult.success("新增失败");
                    }
                }
            }
            return ajax;
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("获取手机号异常，请联系管理员");
        }

    }
    private String httpGet(String url) throws Exception {
        //初始化HttpClient
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //创建HttpGet
        HttpGet httpGet = new HttpGet(url);
        //发起请求，获取response对象
        CloseableHttpResponse response = httpClient.execute(httpGet);
        //获取请求状态码
        //response.getStatusLine().getStatusCode();
        //获取返回数据实体对象
        HttpEntity entity = response.getEntity();
        //转为字符串
        String result = EntityUtils.toString(entity, "UTF-8");
        return result;
    }
    public static String getWxMiniPhone(String sessionkey, String iv, String encryptedData)
            throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidAlgorithmParameterException,
            InvalidKeyException, BadPaddingException, IllegalBlockSizeException, UnsupportedEncodingException {

        byte[] encrypData = Base64Utils.decodeFromString(encryptedData);
        byte[] ivData = Base64Utils.decodeFromString(iv);
        byte[] sessionKey = Base64Utils.decodeFromString(sessionkey);
        String resultString = null;
        AlgorithmParameterSpec ivSpec = new IvParameterSpec(ivData);
        SecretKeySpec keySpec = new SecretKeySpec(sessionKey, "AES");
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
        resultString = new String(cipher.doFinal(encrypData), "UTF-8");
        JSONObject object = JSONObject.parseObject(resultString);
        System.out.println("object = " + object);
        // 拿到手机号码
        String phone = object.getString("phoneNumber");
        return phone;
    }


}
